<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Booth_product_categories_model extends CI_Model 
{ 
	private $_table = 'booth_product_categories';
  	private $_primary = 'id';
  
  	function create($data)
  	{
  		$this->db->insert($this->_table, $data);
  		return $this->db->insert_id();
  	}
  	
	function update($id, $data)
  	{
    	$this->db->where($this->_primary, $id);
    	return $this->db->update($this->_table, $data);
  	}
  	
    public function delete($id)
    {
        $this->db->where($this->_primary, $id);
        return $this->db->delete($this->_table);
    }
    
    public function cnt($booth_id) 
    { 	        
  	    $query = $this->db->query("SELECT COUNT(id) as cnt 
  	                                   FROM `{$this->_table}`
  	                                   WHERE `booth_id` = {$booth_id}
  	                                   ORDER BY `{$this->_primary}` DESC");
  	    return $query->row_array();
    }
  
  	public function getListBoothProductCategories($params = array())
  	{
  	    $condition = 'WHERE 1=1';
  	    $limit = '';
  	    
  	    if (isset($params['start']) && isset($params['limit'])) {
  	        $limit = "LIMIT {$params['start']}, {$params['limit']}";
  	    }
  	    
  	    if (isset($params['parent']) && $params['parent'] === TRUE) {
  	        $condition .= ' AND `parent_id` IS NULL';
  	    }
  	  	if (isset($params['where'])) {
  	        $condition .= $params['where'];
  	    }
  	        
  	    $query = $this->db->query("SELECT * 
  	                                   FROM `{$this->_table}`
  	                                   {$condition}
  	                                   ORDER BY `{$this->_primary}` DESC
  	                                   {$limit}");
  	    return $query->result_array();
  	}

  	function getBoothProductCategoriesById($id)
  	{
  	    $query = $this->db->query("SELECT *
  	                                   FROM  `{$this->_table}`
  	                                   WHERE `id` = {$id}");
  	    return $query->row_array();
  	}
  	
  	public function getTreeBoothProductCategories($booth_id)
  	{       
  	    $treeCategoriesArr = array();
  	    
  	    $query = $this->db->query("SELECT * 
								     FROM `{$this->_table}`
								     WHERE `booth_id` = {$booth_id}
  	                                   ORDER BY parent_id ASC");
  	    $result = $query->result_array();
  	    foreach ($result as $row) {
  	        if (is_null($row['parent_id'])) {
  	            $treeCategoriesArr[$row['id']] = $row;
  	        } else {
  	            $treeCategoriesArr[$row['parent_id']]['child'][] = $row;
  	        }
  	    }
  	    
  	    return $treeCategoriesArr;
  	}
}